package com.dd.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dd.model.ConnectionInfo;
import com.dd.service.JdbcConnectionFactory;
import com.dd.utils.Toast;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class DatabaseManageController implements Initializable {
    @FXML
    private TextField nameField;
    @FXML
    private TextField urlField;
    @FXML
    private TextField userField;
    @FXML
    private TextField passwordField;
    @FXML
    private TableView<ConnectionInfo> databaseTable;
    @FXML
    private TableColumn<ConnectionInfo, String> nameColumn;
    @FXML
    private TableColumn<ConnectionInfo, String> urlColumn;
    @FXML
    private TableColumn<ConnectionInfo, String> userColumn;
    @FXML
    private TableColumn<ConnectionInfo, String> passwordColumn;
    @FXML
    private Button addButton;
    @FXML
    private Button deleteButton;

    private final ObservableList<ConnectionInfo> data = FXCollections.observableArrayList();
    private static final String JSON_PATH = "database-config.json";

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 初始化表格列
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        urlColumn.setCellValueFactory(new PropertyValueFactory<>("url"));
        userColumn.setCellValueFactory(new PropertyValueFactory<>("username"));
        // 修改密码列显示逻辑
        // 在initialize方法中添加passwordColumn的数据绑定
        passwordColumn.setCellValueFactory(new PropertyValueFactory<>("password")); // 假设ConnectionInfo类有password属性的getter方法

        // 保持原有的cellFactory设置
        passwordColumn.setCellFactory(param -> new TableCell<ConnectionInfo, String>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText("****");
                }
            }
        });

        // 加载持久化数据
        loadConfig();
        databaseTable.setItems(data);

        // 新增按钮事件绑定（取消原注释并完善）
        addButton.setOnAction(event -> {
            showAddConnectionDialog(); // 使用对话框输入
        });

        // 新增删除按钮事件绑定
        deleteButton.setOnAction(event -> {
            ConnectionInfo selected = databaseTable.getSelectionModel()
                    .getSelectedItem();
            if (selected != null) {
                data.remove(selected);
                saveConfig();
                Toast.show("删除成功", (Stage) deleteButton.getScene()
                        .getWindow(), 2000);
            } else {
                Toast.show("请选择要删除的连接", (Stage) deleteButton.getScene()
                        .getWindow(), 2000);
            }
        });
    }

    // 新增：弹出对话框输入连接信息
    private void showAddConnectionDialog() {
        Dialog<ConnectionInfo> dialog = new Dialog<>();
        dialog.setTitle("新增数据库连接");
        dialog.initOwner(addButton.getScene()
                .getWindow());

        // 设置对话框内容（输入框）
        VBox dialogVbox = new VBox(8);
        TextField nameField = new TextField();
        nameField.setPromptText("数据库名称");
        TextField serverField = new TextField();
        serverField.setPromptText("服务器地址");
        TextField userField = new TextField();
        userField.setPromptText("用户名");
        TextField passwordField = new TextField();
        passwordField.setPromptText("密码");
        Button testButton = new Button("测试连接");

        String url = StrUtil.format("jdbc:mysql://{}/", serverField.getText());
        ConnectionInfo connectionInfo = new ConnectionInfo(
                nameField.getText(), url, userField.getText(), passwordField.getText(), serverField.getText());
        testButton.setOnAction(e -> testConnection(connectionInfo));
        dialogVbox.getChildren()
                .addAll(nameField, serverField, userField, passwordField, testButton);
        dialog.getDialogPane()
                .setContent(dialogVbox);
        dialog.getDialogPane()
                .getButtonTypes()
                .addAll(ButtonType.OK, ButtonType.CANCEL);

        // 确认按钮逻辑
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == ButtonType.OK) {
                return connectionInfo;
            }
            return null;
        });

        // 保存新增连接
        dialog.showAndWait()
                .ifPresent(info -> {
                    if (info != null && !info.getName()
                            .isEmpty() && !info.getUrl()
                            .isEmpty()) {
                        data.add(info);
                        saveConfig();
                        Toast.show("新增成功", (Stage) addButton.getScene()
                                .getWindow(), 2000);
                    } else {
                        Toast.show("信息不完整，新增失败", (Stage) addButton.getScene()
                                .getWindow(), 2000);
                    }
                });
    }

    private void loadConfig() {
        if (FileUtil.exist(JSON_PATH)) {
            String json = FileUtil.readUtf8String(JSON_PATH);
            List<ConnectionInfo> list = JSONUtil.toList(JSONUtil.parseArray(json), ConnectionInfo.class);
            data.addAll(list);
        }
    }

    private void saveConfig() {
        String json = JSONUtil.toJsonStr(data);
        FileUtil.writeUtf8String(json, JSON_PATH);
    }

    private void testConnection(ConnectionInfo info) {
        try {
            JdbcConnectionFactory.testConnection(info);
            Stage currentStage = (Stage) databaseTable.getScene()
                    .getWindow();
            Toast.show("连接成功", currentStage, 2000); // 显示2秒
        } catch (Exception e) {
            Stage currentStage = (Stage) databaseTable.getScene()
                    .getWindow();
            Toast.show("连接失败：" + e.getMessage(), currentStage, 2000); // 显示3秒
        }
    }

    private void clearFields() {
        nameField.clear();
        urlField.clear();
        userField.clear();
        passwordField.clear();
    }
}